﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ha666.Redis;

namespace CacheEngine.Redis
{
    public class RedisCacheEngine : ICacheEngine
    {
        /// <summary>根据关键字取得缓存数据</summary>
        /// <param name="key">关键字</param>
        /// <returns>缓存数据</returns>
        public T Get<T>(string key)
        {
            ProtobufKey pkey = new ProtobufKey(key);
            object returnVal = null;
            CachedItem cachedItem = null;
            cachedItem = pkey.Get<CachedItem>(0);
            if (cachedItem != null)
            {
                if (cachedItem.ExpirationDate > DateTime.Now)
                    returnVal = cachedItem.Item;
                else
                {
                    pkey.Delete(0);
                }
            }
            return (T)returnVal;
        }
        /// <summary>保存缓存数据</summary>
        /// <param name="key">关键字</param>
        /// <param name="itemToCache">缓存数据</param>
        /// <param name="expirationDate">过期时间</param>
        public void SaveOrUpdate(string key, object itemToCache, DateTime expirationDate)
        {
            ProtobufKey set = new ProtobufKey(key);
            set.Set(0, new CachedItem(itemToCache, expirationDate));
             TimeSpan ts = new TimeSpan();     
            ts = (expirationDate - DateTime.Now);
            set.Expire(0, (long)ts.TotalSeconds);
        }

    }
}
